import $http from '@/http';
/**
 * product vuex
 * 宝贝模块
 */
const State = {
  product: {},
  area: {},
  list: [],
  brand: {}
};

// getters
const Getters = {
  product: state => state.product,
  cat: state => state.cat,
  list: state => state.list,
  brand: state => state.brand
};

// mutations
const Mutations = {
  reset: state => {
    const s = {
      product: {},
      area: {},
      list: [],
      brand: {}
    };
    Object.keys(s).forEach(key => {
      state[key] = s[key];
    });
  },
  SET_PRODUCT: (state, product) => {
    state.product = { ...product };
  },
  SET_LIST: (state, list) => {
    state.list = [...list];
  },
  SET_AREA: (state, area) => {
    state.area = { ...area };
  },
  SET_CAT: (state, { cat, index }) => {
    // 如果数组长度大于index
    if (state.cat.length - 1 >= index) {
      state.cat = state.cat.slice(0, index);
    }
    state.cat.push(cat);
  }
};
// actions
const Actions = {
  storeCat({ commit }, { cat, index }) {
    commit('SET_CAT', { cat, index });
  },
  storeList({ commit }, list) {
    commit('SET_LIST', list);
  },
  ajaxList({ commit }, params) {
    $http.post({ map: 'BRAND', url: 'getUserBrandList' }, params).then(({ data }) => {
      commit('SET_LIST', data['list']);
    });
  },
  storeProduct({ commit }, product) {
    commit('SET_PRODUCT', product);
  },
  storeArea({ commit }, area) {
    commit('SET_AREA', area);
  }
};

export default {
  namespaced: true,
  strict: true,
  state: State,
  getters: Getters,
  actions: Actions,
  mutations: Mutations
};
